import React, { useState } from 'react';
import { Input, Message, Form, Loading } from '@alifd/next';
import styles from './VerificationBlock.module.scss';
import Exception from '@/components/Result';
import { useRequest, getSearchParams, useHistory } from 'ice';
import { codeCheck, accountActive, ActivePrams } from '../service';

const { Item } = Form;

export interface RegisterProps {
  password: string;
  confirmPassword: string;
}

export default function RegisterBlock() {
  const history = useHistory();
  const query = getSearchParams();
  const [postData, setValue] = useState({
    password: '',
    confirmPassword: '',
  });
  const { data, error, loading } = useRequest<string, any[]>(codeCheck, {
    manual: false,
    defaultParams: [query?.activeCode || ''],
    ready: !!query,
  });

  const formChange = (value: RegisterProps) => {
    setValue(value);
  };

  const checkPass = (rule: any, values: string, callback: (errors?: string) => void) => {
    if (values && values !== postData.password) {
      return callback('密码不一致');
    } else {
      return callback();
    }
  };

  const onSuccess = (_: string, params: ActivePrams[]) => {
    Message.success('激活成功');
    history.replace('/user');
  };

  const {
    loading: submitLoading,
    request,
  } = useRequest<string, ActivePrams[]>(accountActive, {
    defaultParams: [],
    onSuccess,
  });

  const handleSubmit = (values: RegisterProps, errors: []) => {
    if (errors) {
      return;
    }
    console.log('values:', values);
    request({
      ...values,
      activeCode: query?.activeCode as string,
    });
  };

  return (
    <div className={styles.RegisterBlock}>
      <Loading visible={loading} fullScreen>
        {!error?.message ? (
          <div className={styles.innerBlock}>
            <a href="#">
              <img
                className={styles.logo}
                src="https://img.alicdn.com/tfs/TB1KtN6mKH2gK0jSZJnXXaT1FXa-1014-200.png"
                alt="logo"
              />
            </a>
            <p className={styles.desc}>
              账号激活 <span className={styles.account}>{data}</span>
            </p>

            {!loading && (
              <Form value={postData} disabled={submitLoading} onChange={formChange} size="large">
                <Item required requiredMessage="必填">
                  <Input.Password
                    name="password"
                    size="large"
                    htmlType="password"
                    placeholder="至少六位密码，区分大小写"
                  />
                </Item>
                <Item required requiredTrigger="onFocus" requiredMessage="必填" validator={checkPass}>
                  <Input.Password name="confirmPassword" size="large" htmlType="password" placeholder="确认密码" />
                </Item>
                <Item>
                  <Form.Submit
                    loading={submitLoading}
                    type="primary"
                    onClick={handleSubmit}
                    className={styles.submitBtn}
                    validate
                  >
                    确认
                  </Form.Submit>
                </Item>
              </Form>
            )}
          </div>
        ) : (
          <Exception
            statusCode="校验失败"
            description="请核对并修改信息后，再重新提交。"
            image="https://img.alicdn.com/tfs/TB1VOSVoqL7gK0jSZFBXXXZZpXa-72-72.png"
            buttonBackDesc="返回首页"
            onButtonBack={() => history.replace('/user')}
          />
        )}
      </Loading>
    </div>
  );
}
